using UnityEngine;
using System.Collections;

public class Escada : MonoBehaviour 
{
	public Vector3[] positions = new Vector3[8];
	private Color[] triangleColors = new Color[8];
	private int objectsPlaced = 0;
	public GameObject pistaPrefab;
	
	void Start()
	{
		for (int i = 0; i < renderer.materials.Length; i+=2) 
		{
			triangleColors[i] = renderer.materials[i].color;
			renderer.materials[i].color = Color.white;
		}
	}
	
	void Update()
	{
		if(objectsPlaced == 4)
		{
			ColorFactory.stage = 2;
		}

		if(ColorFactory.stage == 2)
		{
			for (int i = 0; i < renderer.materials.Length; i+=2) 
			{
				renderer.materials[i].color = triangleColors[i];
			}
			
			ColorFactory.stage = 3;
		}
		
		if(objectsPlaced == 8 && ColorFactory.stage == 3)
		{
			ColorFactory.stage = 4;
		}
		
		if(ColorFactory.stage == 5)
		{
			Instantiate(pistaPrefab, pistaPrefab.transform.position, Quaternion.Euler(0,180,0));
			ColorFactory.stage = 6;
		}
	}
	
	void OnCollisionEnter(Collision other)
	{
		if(other.gameObject.layer == 12)
		{
			GameObject cubo = other.gameObject;
			
			for (int i = 0; i < renderer.materials.Length; i++)
			{
				if(ColorFactory.stage == 1)
				{
					if(cubo.renderer.material.color == renderer.materials[i].color)
					{
						cubo.transform.rotation = Quaternion.identity;
						cubo.rigidbody.Sleep();
						cubo.rigidbody.useGravity = false;
						cubo.layer = 10;
						cubo.transform.position = positions[i];
						
						Player.ThrowAwawyCube();
						objectsPlaced++;
					}
				}
				else
				{
					if(cubo.transform.GetChild(0).renderer.material.color == renderer.materials[i].color)
					{		
						cubo.transform.rotation = Quaternion.Euler(45, 0, 0);
						cubo.rigidbody.Sleep();
						cubo.rigidbody.useGravity = false;
						cubo.layer = 10;
						cubo.transform.position = positions[i];
						
						Player.ThrowAwawyCube();
						objectsPlaced++;
					}
				}
				
			}
		}
	}
}
